package com.fansl.allround.ucenter.controller;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fansl.allround.common.core.constant.enums.SexEnum;
import com.fansl.allround.common.core.constant.enums.UserStatusEnum;
import com.fansl.allround.common.core.util.WebUtils;
import com.fansl.allround.common.core.validator.EmailValidator;
import com.fansl.allround.common.core.validator.NotNullValidator;
import com.fansl.allround.common.core.constant.enums.OauthTypeEnum;
import com.fansl.allround.ucenter.api.common.constant.UcenterResult;
import com.fansl.allround.ucenter.api.common.constant.UcenterResultEnum;
import com.fansl.allround.ucenter.api.dto.UserRegisterDTO;
import com.fansl.allround.ucenter.api.entity.UcenterUser;
import com.fansl.allround.ucenter.api.vo.UcenterUserOauthVO;
import com.fansl.allround.ucenter.service.UcenterUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author fansl
 * @Description: TODO
 * @date 2019/9/25 16:57
 */
@RestController
@RequestMapping("/register")
@AllArgsConstructor
@Slf4j
public class RegisterController {
    private final UcenterUserService ucenterUserService;

    /**
     * 注册信息
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/user")
    public UcenterResult register(@RequestBody UserRegisterDTO userRegisterDTO){
        ComplexResult result = FluentValidator.checkAll()
                .on(userRegisterDTO.getNickname(),new NotNullValidator("昵称"))
                .on(userRegisterDTO.getPassword(),new NotNullValidator("密码"))
                .on(userRegisterDTO.getEmail(),new EmailValidator())
                .on(userRegisterDTO.getEmailCode(),new NotNullValidator("验证码"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if(!result.isSuccess()){
            return new UcenterResult(UcenterResultEnum.FAILED,result.getErrors());
        }
        boolean b = ucenterUserService.register(userRegisterDTO);

        return new UcenterResult(UcenterResultEnum.SUCCESS,b);
    }
    /**
     * 查询当前用户是否已经被注册
     * @param email
     * @return
     */
    @PostMapping("/check")
    public UcenterResult checkEmail(@RequestParam String email){
        ComplexResult result = FluentValidator.checkAll()
                .on(email,new EmailValidator())
                .doValidate()
                .result(ResultCollectors.toComplex());
        if(!result.isSuccess()){
            return new UcenterResult(UcenterResultEnum.FAILED,result.getErrors());
        }
        //查询当前用户是否已经被注册
        UcenterUser ucenterUser =
                ucenterUserService.getOne(Wrappers.<UcenterUser>lambdaUpdate().eq(UcenterUser::getEmail,email));
        if(ucenterUser!=null){
            new UcenterResult(UcenterResultEnum.FAILED,false);
        }
        return new UcenterResult(UcenterResultEnum.SUCCESS,true);
    }

    /**
     * 发送注册验证码
     * @param email
     * @return
     */
    @PostMapping("/code")
    public UcenterResult registerCode(@RequestParam String email){
        ComplexResult result = FluentValidator.checkAll()
                .on(email,new EmailValidator())
                .doValidate()
                .result(ResultCollectors.toComplex());
        if(!result.isSuccess()){
            return new UcenterResult(UcenterResultEnum.FAILED,result.getErrors());
        }
        //发送验证码
        boolean b = ucenterUserService.sendRegisterCode(email);
        return new UcenterResult(UcenterResultEnum.SUCCESS,b);
    }

    @GetMapping("/weibo")
    public void weiboLogin(HttpServletRequest request){
        String url =
                "https://api.weibo.com/oauth2/authorize?client_id=3646475573&response_type=code&redirect_uri=http://8p4my9.natappfree.cc/ucenter/register/weibo";
        System.out.println("weiboLogin");
        String weiboAppId = "3646475573";
        String weiboAppSecret = "2aba2160660c4735f974951033db3453";
        String authPath = "http://8p4my9.natappfree.cc/ucenter/register/weibo";
        String code = request.getParameter("code");
        String params = "client_id=" + weiboAppId
                + "&client_secret=" + weiboAppSecret
                + "&grant_type=authorization_code"
                + "&redirect_uri=" + URLUtil.encode(authPath)
                + "&code=" + code;
        // 用code换取accessToken
        String result = HttpUtil.post("https://api.weibo.com/oauth2/access_token", params);
        log.info("获取微博的accessToken,result:{}",JSONObject.toJSONString(result));
        Map<String, Object> resp = JSONObject.parseObject(result);

        Integer errorCode = (Integer)resp.get("error_code");
        String error = (String)resp.get("error");
        String errorMsg = (String)resp.get("error_description");
        String accessToken = (String)resp.get("access_token");
        // 这个uid就是微博用户的唯一用户ID，可以通过这个id直接访问到用户微博主页
        String uid = (String)resp.get("uid");
        // 有效期，单位秒
        int expires = (Integer)resp.get("expires_in");
        UcenterUserOauthVO ucenterUserOauthVO = ucenterUserService.getByOauthType(uid,OauthTypeEnum.WEIBO);
        if(ucenterUserOauthVO==null){
            //获取微博用户信息
            // 用uid和accessToken换取用户信息
            String result1 = HttpUtil.get("https://api.weibo.com/2/users/show.json?access_token="+accessToken+"&uid="+uid);
            log.info("用uid和accessToken换取用户信息,result:{}",JSONObject.toJSONString(result1));
            Map<String, Object> userInfo = JSONObject.parseObject(result1);

            errorCode = (Integer)userInfo.get("error_code");
            error = (String)userInfo.get("error");
            errorMsg = (String)userInfo.get("error_description");
            String nickname = (String)userInfo.get("screen_name");
            // 微博180*180高清头像
            String avatar = (String)userInfo.get("avatar_large");
            String gender = (String)userInfo.get("gender");
            SexEnum sexEnum = "m".equals(gender) ? SexEnum.MALE : ("f".equals(gender) ? SexEnum.FEMALE : SexEnum.UNKNOWN);
            UcenterUser ucenterUser = new UcenterUser();
            ucenterUser.setNickname(nickname)
                    .setStatus(UserStatusEnum.NORMAL.getCode())
                    .setCreateIp(WebUtils.getIP())
                    .setAvatar(avatar)
                    .setSex(sexEnum.getType());
            //创建新的用户
            ucenterUserService.registerUseOauth(ucenterUser,uid,OauthTypeEnum.WEIBO);
        }
    }
    @GetMapping("/cancle")
    public void weiboLoginCancle(HttpServletRequest request){
        System.out.println("cancle");
    }
}
